//
//  HMPhotoSelectorController.swift
//  sinaweibo
//
//  Created by WGP on 16/4/24.
//  Copyright © 2016年 WGP. All rights reserved.
//

import UIKit
import HMImagePicker

private let reuseIdentifier = "Cell"

class HMPhotoSelectorController: UICollectionViewController {

//    记录用户选择的图片
    var photos = [UIImage]()
    
    private var selectedAssets:[PHAsset]?
    
    private var maxCount =  6
    
    private var layout = UICollectionViewFlowLayout()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView?.backgroundColor = UIColor.whiteColor()
        self.collectionView!.registerClass(HMPhotoSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
    }

    init()
    {
        super.init(collectionViewLayout: layout)
        layout.itemSize = CGSize(width: 80, height: 80)
        layout.collectionView?.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 0, right: 10)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    // MARK: UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return photos.count < maxCount ? photos.count + 1 : maxCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! HMPhotoSelectorCell
    
        cell.backgroundColor = UIColor.brownColor()
        
        cell.delegate = self
        
        if indexPath.item < photos.count
        {
         cell.image = photos[indexPath.item]
        }
        else
        {
            cell.setupButton()
        }
        return cell
    }

}

extension HMPhotoSelectorController: HMPhotoSelectorCellDelegete
{
    func photoSelectorCellDidClickAddButton(cell: HMPhotoSelectorCell) {
        
        let picker = HMImagePickerController(selectedAssets: selectedAssets)
        
        picker.pickerDelegate = self
        
        picker.targetSize = CGSize(width: 600, height: 600)
        
        picker.maxPickerCount = maxCount
        
        presentViewController(picker, animated: true) { () -> Void in
            
        }
    }
    
    func photoSelectorCellDidClickDeleteButton(cell: HMPhotoSelectorCell) {
        
        let indexPath = collectionView!.indexPathForCell(cell)!
        
//        https://github.com/itheima-developer/HMImagePicker
        
        photos.removeAtIndex(indexPath.item)
        self.selectedAssets?.removeAtIndex(indexPath.item)
        
        collectionView?.reloadData()
    }
}

extension HMPhotoSelectorController: HMImagePickerControllerDelegate
{
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        
        self.photos = images
        self.selectedAssets = selectedAssets
        
        collectionView?.reloadData()
        picker.dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
}

extension HMPhotoSelectorController: UIImagePickerControllerDelegate,UINavigationControllerDelegate
{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let newWidth: CGFloat = 300
        let newHeight = newWidth * image.size.height/image.size.width
        
        image.GP_AsynDrawImage(CGSize(width: newWidth, height: newHeight), bgColor: UIColor.whiteColor(), isCorner: false) { (image) -> () in
            
            self.photos.append(image)
            self.collectionView?.reloadData()
            
            picker.dismissViewControllerAnimated(true, completion: { () -> Void in
                
            })
        }
    }
}

protocol HMPhotoSelectorCellDelegete: NSObjectProtocol
{
    func photoSelectorCellDidClickAddButton(cell: HMPhotoSelectorCell)
    func photoSelectorCellDidClickDeleteButton(cell: HMPhotoSelectorCell)
}

class HMPhotoSelectorCell: UICollectionViewCell{
    
    weak var delegate: HMPhotoSelectorCellDelegete?
    
    var image: UIImage?
    {
        didSet
        {
            addButton.setImage(image, forState: .Normal)
            
            deleteButton.hidden = false
        }
    }
    
    func setupButton()
    {
        addButton.setImage(UIImage(named: "compose_pic_add"), forState: .Normal)
        
        deleteButton.hidden = true
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI()
    {
        contentView.addSubview(addButton)
        contentView.addSubview(deleteButton)
        
        addButton.translatesAutoresizingMaskIntoConstraints = false
        deleteButton.translatesAutoresizingMaskIntoConstraints = false
        
//        VFL
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ab]-0-|", options: [], metrics: nil, views: ["ab":addButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ab]-0-|", options: [], metrics: nil, views: ["ab":addButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[db]-0-|", options: [], metrics: nil, views: ["db":deleteButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[db]", options: [], metrics: nil, views: ["db":deleteButton]))
    }
    
    @objc private func didClickDeleteButton()
    {
        delegate?.photoSelectorCellDidClickDeleteButton(self)
    }
    
    @objc private func didClickAddButton()
    {
        delegate?.photoSelectorCellDidClickAddButton(self)
    }
    
//    MARK: - 懒加载
    private lazy var deleteButton: UIButton =
    {
        let button = UIButton()
        
//        设置
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        button.addTarget(self, action: Selector("didClickDeleteButton"), forControlEvents: .TouchUpInside)
        
        return button
    }()
    
    private lazy var addButton: UIButton =
    {
        let button = UIButton()
        
        button.setImage(UIImage(named: "compose_pic_add"), forState: .Normal)
        button.addTarget(self, action: Selector("didClickAddButton"), forControlEvents: .TouchUpInside)
        
        return button
    }()
}















